﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Nate_sRoguelikeGameXNA.GameObjects.Architecture;

namespace Nate_sRoguelikeGameXNA.Levels
{
    class SplitRectangle
    {
        public Rectangle Source { get; private set; }
        public SplitRectangle Parent { get; private set; }
        public SplitRectangle[] SubRectangles { get; private set; }
        public int Area { get; set; }
        public Room Room { get; set; }

        public SplitRectangle(SplitRectangle parent, Rectangle source)
        {
            Parent = parent;
            Source = source;
            SubRectangles = new SplitRectangle[0];
            Area = source.GetArea();
        }

        public Room CreateRoom(Level level)
        {
            Room = new Room(level, GameArchitecture.StoneWall, Source);
            return Room;
        }

        public SplitRectangle[] Split()
        {
            if (Source.GetArea() <= 96 || (Source.Width < 14 && Source.Height < 14))
                return SubRectangles;

            SubRectangles = new SplitRectangle[2];
            bool splitX;
            if (Source.Width < 12)
                splitX = false;
            else if (Source.Height < 12)
                splitX = true;
            else
                splitX = Convert.ToBoolean(Game.Roll(1, 2, true));

            var a =
                new SplitRectangle(this, new Rectangle(Source.Left, Source.Top,
                                                 splitX
                                                     ? Game.Roll(1, Source.Width - 7, 7)
                                                     : Source.Width,
                                                 splitX
                                                     ? Source.Height
                                                     : Game.Roll(1, Source.Height - 7, 7)));
            SubRectangles[0] = a;
            SubRectangles[1] = splitX
                                   ? new SplitRectangle(this, new Rectangle(a.Source.Right + 1, Source.Top,
                                                                      Source.Right - a.Source.Right - 1,
                                                                      Source.Height))
                                   : new SplitRectangle(this, new Rectangle(Source.Left, a.Source.Bottom + 1, Source.Width,
                                                                      Source.Bottom - a.Source.Bottom - 1));
            return SubRectangles;
        }

    }
}
